package com.example.serviceprovider.controller;

import com.example.serviceprovider.model.Product;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/products")
public class ProductController {

    private final Map<Long, Product> products = new ConcurrentHashMap<>();
    private final AtomicLong counter = new AtomicLong();

    @Autowired // 已添加，用于环境注入
    private Environment environment; // 已添加

    private String getInstancePortInfo() { // 已添加辅助方法
        return " [Provider instance on port: " + environment.getProperty("local.server.port") + "]";
    }

    @PostConstruct
    public void init() {
        // 初始化一些数据
        products.put(counter.incrementAndGet(), new Product(1L, "Laptop", 1200.99));
        products.put(counter.incrementAndGet(), new Product(2L, "Mouse", 25.50));
        products.put(counter.incrementAndGet(), new Product(3L, "Keyboard", 75.00));
    }

    // GET: 获取所有产品
    @GetMapping
    public ResponseEntity<List<Product>> getAllProducts() {
        System.out.println("Provider: GET /products called");
        System.out.println("Provider: GET /products called" + getInstancePortInfo());
        
        // 模拟随机失败 (30%概率失败，用于测试断路器A)
        if (Math.random() < 0.4) {
            System.out.println("模拟服务失败: 随机异常");
            throw new RuntimeException("模拟随机服务异常");
        }
        
        return ResponseEntity.ok(products.values().stream().collect(Collectors.toList()));
    }

    // GET: 根据ID获取产品
    @SneakyThrows
    @GetMapping("/{id}")
    public ResponseEntity<Product> getProductById(@PathVariable Long id) {
        System.out.println("Provider: GET /products/" + id + " called");
        System.out.println("Provider: GET /products/" + id + " called" + getInstancePortInfo());
        
        // 模拟慢调用和失败场景
        if (id == 999L) {
            // 模拟慢调用，超过2秒阈值
            Thread.sleep(3000);
            System.out.println("模拟慢调用: 延迟3秒");
        } else if (id == 888L) {
            // 模拟服务异常
            throw new RuntimeException("模拟服务异常");
        }
        
        Product product = products.get(id);
        if (product != null) {
            return ResponseEntity.ok(product);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // POST: 创建新产品
    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        long newId = counter.incrementAndGet();
        product.setId(newId);
        products.put(newId, product);
        System.out.println("Provider: POST /products called with product: " + product);
        System.out.println("Provider: POST /products called with product: " + product + getInstancePortInfo());
        return ResponseEntity.status(HttpStatus.CREATED).body(product);
    }

    // PUT: 更新产品
    @PutMapping("/{id}")
    public ResponseEntity<Product> updateProduct(@PathVariable Long id, @RequestBody Product productDetails) {
        System.out.println("Provider: PUT /products/" + id + " called with product: " + productDetails);
        System.out.println("Provider: PUT /products/" + id + " called with product: " + productDetails + getInstancePortInfo());
        Product product = products.get(id);
        if (product != null) {
            product.setName(productDetails.getName());
            product.setPrice(productDetails.getPrice());
            products.put(id, product);
            return ResponseEntity.ok(product);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    // DELETE: 删除产品
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteProduct(@PathVariable Long id) {
        System.out.println("Provider: DELETE /products/" + id + " called");
        System.out.println("Provider: DELETE /products/" + id + " called" + getInstancePortInfo());
        Product removedProduct = products.remove(id);
        if (removedProduct != null) {
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}